/*
Copyright 2009 Johan Maasing, Mikael Forsberg

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package com.google.code.pj2r.beanutils;

import com.google.code.pj2r.Marshaller;
import com.google.code.pj2r.MarshallingException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;

public class BeanUtilsMarshaller implements Marshaller {

	public void marshal(HttpServletRequest request, Object result) throws MarshallingException {
		if (request == null) {
			throw new IllegalArgumentException("Request may not be null");
		}
		if (result == null) {
			throw new IllegalArgumentException("Result may not be null");
		}

		try {
			BeanUtils.populate(result, getDataMap(request));
		} catch (IOException ex) {
			throw new MarshallingException(ex);
		} catch (IllegalAccessException ex) {
			throw new MarshallingException(ex);
		} catch (InvocationTargetException ex) {
			throw new MarshallingException(ex);
		}
	}

	/**
	 * Get the data the request contains.
	 * @param request The request, may not be null.
	 * @return The map of the data in the request.
	 * @throws IOException
	 * @throws MarshallingException If the request can not be marshalled.
	 */
	protected Map getDataMap(HttpServletRequest request) throws IOException, MarshallingException {
		return request.getParameterMap();
	}
}
